package com.qf.iot.utils;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.iot.entity.QfTenant;

import java.util.Calendar;
import java.util.Date;

/**
 * 作者：Bin
 * 时间：2023/10/12
 * 描述：键盘敲烂，薪资过万
 */
public class GetJwtToken {

    private static String salt = "db";
    private static final String key = "userInfo";

    public static String getTokenExpireInHour(Object object, int hour) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, hour);
        Date time = instance.getTime();
        String sign = JWT.create().withExpiresAt(time).withClaim(key, JSONUtil.toJsonStr(object)).sign(Algorithm.HMAC256(salt));
        return sign;
    }

    public static String getTokenExpireInMinute(Object object, int minute) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, minute);
        Date time = instance.getTime();
        String sign = JWT.create().withExpiresAt(time).withClaim(key, object.toString()).sign(Algorithm.HMAC256(salt));
        return sign;
    }

    public static QfTenant verify(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(salt)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        String userInfo = verify.getClaim(key).asString();
        return JSONUtil.toBean(userInfo, QfTenant.class);
    }
}
